import json
import time

from lxml import etree

import requests


# 视频下载器

# 获取视频信息
def get_video_list(keyword, pn=1, rn=10):
    payload = {}
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
        'Connection': 'keep-alive',
        'Upgrade-Insecure-Requests': '1',
        'TE': 'Trailers'}
    url = "https://haokan.baidu.com/videoui/page/search?pn=%s&rn=%s&_format=json&tab=video&query=%s"

    response = requests.request("GET", url % (pn, rn, keyword), headers=headers, data=payload)
    response.encoding = response.apparent_encoding
    text = json.loads(response.text)
    if text['status'] == 0:
        content_list = text["data"]["response"]["list"]
        # 保存vid
        ret_list = []
        for content in content_list:
            ret_list.append(content['vid'])
        return ret_list


# 提取视频播放url
def get_video(vid):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
        'Connection': 'keep-alive',
        'Upgrade-Insecure-Requests': '1',
        'TE': 'Trailers'}
    download_url = "https://haokan.baidu.com/v?vid=%s"
    response = requests.request("GET", download_url % vid, headers=headers)
    response.encoding = response.apparent_encoding
    html = etree.HTML(response.text)
    html_text = html.xpath("//script[@id='_page_data']")
    init_data = html_text[0].text
    data = init_data[str(init_data).find("=") + 1:str(init_data).rfind("document.") - 49]
    data_json = json.loads(data)
    curVideoMeta = data_json['curVideoMeta']
    clarityUrl = curVideoMeta['clarityUrl']
    # 超清
    gc_clarity_url = list(filter(lambda x: x['key'] == 'sc', clarityUrl))
    if len(gc_clarity_url) <= 0:
        # 高清
        gc_clarity_url = list(filter(lambda x: x['key'] == 'hd', clarityUrl))
        if len(gc_clarity_url) <= 0:
            # 标清
            gc_clarity_url = list(filter(lambda x: x['key'] == 'sd', clarityUrl))
    if len(gc_clarity_url) <= 0:
        return ""
    else:
        return gc_clarity_url[0]['url']


# 下载视频
def download_video(video_url):
    # 定义存储的文件名
    savePath = str(time.time()) + '.mp4'
    res = requests.get(video_url)
    try:
        with open(savePath, 'wb') as f:
            f.write(res.content)
    except Exception as e:
        print(e)
    finally:
        if f:
            f.close()


def gather_video(key_word):
    # 1.获取视频vid
    vid_list = get_video_list(keyword=key_word)
    print(f"1.获取视频vid{vid_list}")
    # 2.获取视频播放地址
    video_url_list = []
    for vid in vid_list:
        video_url = get_video(vid)
        if video_url:
            video_url_list.append(video_url)
    print(f"2.获取视频播放地址{video_url_list}")
    # 3.下载到本地
    for video_url in video_url_list:
        download_video(video_url)
        print(f"3.视频{video_url}下载完成")


gather_video("哆啦A梦")
